<?php
class Admin_Model_Users extends Zend_Db_Table {

    public $_name = 'user';
	
	public function __construct($config = array())
    {
        parent::__construct($config);
		$writer = new Zend_Log_Writer_Stream(APPLICATION_PATH.'/log.txt');
		$this->logger = new Zend_Log($writer);
    }
	
	// Đếm số lượng record thỏa mãn các điều kiện trong parameter -- Coder: Cùi Bắp
	public function count($parameter){
        $db = Zend_Db_Table::getDefaultAdapter();        
        $where = "(1=1)";
        $param = array();
        if($parameter['searchString'] !=""){
            $searchString = strtolower($parameter['searchString']);
            $where .= " and LCASE(CONCAT(user.FIRSTNAME, ' ', user.LASTNAME)) LIKE '%".$searchString."%'";
        }
		if($parameter['searchEmail'] !=""){		
            $searchEmail = strtolower($parameter['searchEmail']);
			//$searchEmail = 
            $where .= " and user.EMAIL = '". $searchEmail."'";
        }
        if($parameter['searchRole']!=""){
            $searchRole = (int) $parameter['searchRole'];
            $where .= " and user.ROLEID = $searchRole";
        }
		if($parameter['searchStatus']!=""){
            $searchStatus = (int)$parameter['searchStatus'];
            $where .= " and user.STATUS = $searchStatus";
        }
        $sql = "select count(*) as COUNT from ".$this->_name." user WHERE $where";
        $result = $db->query($sql)->fetch();
        return $result['COUNT'];
    }

	// Lấy toàn bộ record trong table User - Coder: Cùi Bắp
    public function SelectAll($parameter,$limit,$offset) {
		
		$select = $this->getAdapter()->select();        
        $where = "(1=1)";
        
		$param = array();
        if($parameter['searchString'] !=""){
            $searchString = strtolower($parameter['searchString']);
            $where .= " and LCASE(CONCAT(user.FIRSTNAME, ' ', user.LASTNAME))  LIKE '%".$searchString."%'";
        }
		if($parameter['searchEmail'] !=""){
            $searchEmail = strtolower($parameter['searchEmail']);
             $where .= " and user.EMAIL = '". $searchEmail."'";
        }
        if($parameter['searchRole']!=""){
            $searchRole = (int) $parameter['searchRole'];
            $where .= " and user.ROLEID = $searchRole";
        }
		if($parameter['searchStatus']!=""){
            $searchStatus = (int)$parameter['searchStatus'];
            $where .= " and user.STATUS = $searchStatus";
        }
		
		$select	-> from(array('user'), array('USERID','EMAIL','FIRSTNAME','LASTNAME','ROLEID','STATUS'))
				-> join(array('role'),"`user`.`ROLEID` = `role`.`ROLEID`",array('NAME'))
				-> where($where)
				-> limit($limit,$offset);
		
        $result = $this->getDefaultAdapter()->fetchAll($select);
		/* print_r($select->__toString()); */
        return $result;
    }
	
	/* 	Thêm  1 User 
		Coder: Cùi Bắp */
    public function addNewUser($Params){       
        $db = $this->getDefaultAdapter();
        $data = array(
            'FIRSTNAME' => $Params['FIRSTNAME'],
            'LASTNAME' => $Params['LASTNAME'],
            'EMAIL' => $Params['EMAIL'],
            'PASSWORD' => $Params['PASSWORD'],
            'STATUS' => (int) $Params['STATUS'],
            'ROLEID' => $Params['ROLEID']
        );
        if($Params['PASSWORD'] != ""){
            $data['PASSWORD'] = md5($Params['PASSWORD']);
        }
             
        try {
            $db->insert($this->_name, $data);
        }catch (Zend_Exception $e) {
            echo ($e->getMessage());
            exit;
        }
    }
	
	/* 	Sửa 1 User 
		Coder: Cùi Bắp */
	public function updateUser($Params){
		$id = $Params['USERID'];
		$db = $this->getDefaultAdapter();
		$data = array();
        if(isset($Params['FIRSTNAME'])) $data['FIRSTNAME'] = $Params['FIRSTNAME'];
		if(isset($Params['LASTNAME'])) $data['LASTNAME'] = $Params['LASTNAME'];
		if(isset($Params['EMAIL'])) $data['EMAIL'] = $Params['EMAIL'];     
		if(isset($Params['STATUS'])) $data['STATUS'] = $Params['STATUS'];     
		if(isset($Params['ROLEID'])) $data['ROLEID'] = $Params['ROLEID'];     
		if(isset($Params['PASSWORD'])) $data['PASSWORD'] = md5($Params['PASSWORD']);     
        try {
			$db->update($this->_name, $data,"USERID = ".$id);
        }catch (Zend_Exception $e) {
            echo ($e->getMessage());
            exit;
        }
	}
	
    public function GetUserByUser($username) {
        $db = Zend_Db_Table::getDefaultAdapter();

        $sql = "select * from $this->_name where username='".$username."'";
        $stmt = $db->query($sql);
        $r = $stmt->fetch();
        if ($r)
            return 1;
        else return 0;
    }
    public function FindById($id) {
        //Thực hiện query
        $result = $this->getDefaultAdapter()->query("
			SELECT
				*
			FROM
				$this->_name
			WHERE
				ID = ?
		", $id);
        return $result->fetch();
    }
    public function findByIdJoinCompany($id) {
        $select = $this->select();
        $where = $this->getAdapter()->quoteInto('ID_U = ?', $id);
        $select->from($this,array("ID_U","USERNAME","EMAIL","SOCMND","FULLNAME","PHONE","ROLE","STATUS","ID_COMPANY"))
               ->join(array("com"=>"company","ha_users.ID_COMPANY = com.id"),array('id as idcompany','name'))
               ->where($where);
        $data = $this->fetchAll($select);
        return $data;
    }
    public function GetListUsers(){
      $sql = "select ID_U,FULLNAME from $this->_name";
      $db = Zend_Db_Table::getDefaultAdapter();
      $r = $db->query($sql);
      return $r->fetchAll();
     }

    public function GetUsersById($id) {
          $sql = "select * from $this->_name where ID_U = '".$id."'";
          $db = Zend_Db_Table::getDefaultAdapter();
          $r = $db->query($sql);
          return $r->fetch();
    }
}